import { Module } from 'vuex'
import _ from 'lodash'
import historySearchStateTypes from './types'
import RootStateTypes from '../../types'
import { setStore, getStore } from '@/utils/store'

const historySearchModule: Module<historySearchStateTypes, RootStateTypes> = {
  namespaced: true,
  state: {
    historySearchList:
      getStore({
        name: 'historySearchList'
      }) || []
  },
  mutations: {
    SET_HISTORY_LIST(state: historySearchStateTypes, historyList: string[]) {
      state.historySearchList = historyList
    }
  },
  actions: {
    addHistoryRead({ state, commit }, historyItem: string) {
      return new Promise((resolve, reject) => {
        try {
          const historySearchList: string[] = _.cloneDeep(state.historySearchList)
          const index = historySearchList.findIndex((item) => {
            return item === historyItem
          })
          if (index > -1) {
            historySearchList.splice(index, 1)
          }
          historySearchList.unshift(historyItem)
          commit('SET_HISTORY_LIST', historySearchList)
          setStore({ name: 'historySearchList', content: historySearchList })
          resolve('ok')
        } catch (error) {
          reject(error)
        }
      })
    },

    clearHistoryList({ commit }) {
      commit('SET_HISTORY_LIST', [])
    }
  }
}

export default historySearchModule
